import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**聊天玩家信息属性枚举*/
export const enum E_ChatMessage {
	/**频道*/
	CHANNEL = 0,
	/**发送者类型*/
	SENDER_MAIN = 1,
	/**发送者类型2(预留)*/
	SENDER_SUB = 2,
	/**发送时间*/
	SEND_TIME = 3,
	/**数值参*/
	PARAM_NUM = 4,
	/**字符参*/
	PARAM_STR = 5,
	/**枚举数量*/
	EnumCount = 6
}


/**聊天玩家信息*/
export class ChatMessage {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_CHAT_MESSAGE_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_CHAT_MESSAGE_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ChatMessage[] = [];

	/**创建入口*/
	public static create(json?: string): ChatMessage {
		const c = this.POOL.pop() || new ChatMessage();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**频道 (uint8)*/
	protected _channel: number;
	/**发送者类型 (uint8)*/
	protected _senderMain: number;
	/**发送者类型2(预留) (uint8)*/
	protected _senderSub: number;
	/**发送时间 (long)*/
	protected _sendTime: number;
	/**数值参 (uint8, long)*/
	protected _paramNum: HashMap<number, number> = null;
	/**字符参*/
	protected _paramStr: HashMap<number, string> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ChatMessage.POOL.indexOf(this) === -1) {
			ChatMessage.POOL.push(this);
		}
	}

	/**频道*/
	public get channel() {
		return this._channel;
	}


	/**频道*/
	public set channel(v: number) {
		this._channel = v;
	}


	/**发送者类型*/
	public get senderMain() {
		return this._senderMain;
	}


	/**发送者类型*/
	public set senderMain(v: number) {
		this._senderMain = v;
	}


	/**发送者类型2(预留)*/
	public get senderSub() {
		return this._senderSub;
	}


	/**发送者类型2(预留)*/
	public set senderSub(v: number) {
		this._senderSub = v;
	}


	/**发送时间*/
	public get sendTime() {
		return this._sendTime;
	}


	/**发送时间*/
	public set sendTime(v: number) {
		this._sendTime = v;
	}


	/**设置数值参*/
	public putParamNum(k: number, v: number): number {
		const ov = this._paramNum.put(k, v);
		return ov || 0;
	}


	/**获取数值参*/
	public getParamNum(k: number) {
		return this._paramNum.get(k) || 0;
	}


	/**删除数值参*/
	public removeParamNum(k: number): number {
		const ov = this._paramNum.remove(k);
		return ov || 0;
	}


	/**获取数值参映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getParamNumKeys(): number[] {
		return this._paramNum.getKeys();
	}


	/**获取数值参映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getParamNumValues(): number[] {
		return this._paramNum.getValues();
	}


	/**清空数值参映射表*/
	public clearParamNumMap(): void {
		this._paramNum.clear();
	}


	/**设置字符参*/
	public putParamStr(k: number, v: string): string {
		const ov = this._paramStr.put(k, v);
		return ov;
	}


	/**获取字符参*/
	public getParamStr(k: number) {
		return this._paramStr.get(k);
	}


	/**删除字符参*/
	public removeParamStr(k: number): string {
		const ov = this._paramStr.remove(k);
		return ov;
	}


	/**获取字符参映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getParamStrKeys(): number[] {
		return this._paramStr.getKeys();
	}


	/**获取字符参映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getParamStrValues(): string[] {
		return this._paramStr.getValues();
	}


	/**清空字符参映射表*/
	public clearParamStrMap(): void {
		this._paramStr.clear();
	}



	/**通过枚举获取值*/
	public getV(k: E_ChatMessage): any {
		switch (k) {
			case E_ChatMessage.CHANNEL: return this._channel;
			case E_ChatMessage.SENDER_MAIN: return this._senderMain;
			case E_ChatMessage.SENDER_SUB: return this._senderSub;
			case E_ChatMessage.SEND_TIME: return this._sendTime;
			case E_ChatMessage.PARAM_NUM: return this._paramNum;
			case E_ChatMessage.PARAM_STR: return this._paramStr;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ChatMessage, v: any): void {
		switch (k) {
			case E_ChatMessage.CHANNEL: this._channel = v; break;
			case E_ChatMessage.SENDER_MAIN: this._senderMain = v; break;
			case E_ChatMessage.SENDER_SUB: this._senderSub = v; break;
			case E_ChatMessage.SEND_TIME: this._sendTime = v; break;
			case E_ChatMessage.PARAM_NUM: this._paramNum = v; break;
			case E_ChatMessage.PARAM_STR: this._paramStr = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//频道
		this._channel = 0;
		//发送者类型
		this._senderMain = 0;
		//发送者类型2(预留)
		this._senderSub = 0;
		//发送时间
		this._sendTime = 0;
		//数值参
		if (this._paramNum) {
			this._paramNum.clear();
		}
		else {
			this._paramNum = new HashMap<number, number>();
		}
		//字符参
		if (this._paramStr) {
			this._paramStr.clear();
		}
		else {
			this._paramStr = new HashMap<number, string>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._channel) {
			json.channel = this._channel;
		}
		if (this._senderMain) {
			json.senderMain = this._senderMain;
		}
		if (this._senderSub) {
			json.senderSub = this._senderSub;
		}
		if (this._sendTime) {
			json.sendTime = this._sendTime;
		}
		if (this._paramNum.size() > 0) {
			const ks = this._paramNum.getKeys();
			const vs = this._paramNum.getValues();
			json.paramNum = [ks, vs];
		}
		if (this._paramStr.size() > 0) {
			const ks = this._paramStr.getKeys();
			const vs = this._paramStr.getValues();
			json.paramStr = [ks, vs];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.channel) {
			this._channel = json.channel;
		}
		if (json.senderMain) {
			this._senderMain = json.senderMain;
		}
		if (json.senderSub) {
			this._senderSub = json.senderSub;
		}
		if (json.sendTime) {
			this._sendTime = json.sendTime;
		}
		if (json.paramNum) {
			const ks: number[] = json.paramNum[0];
			const vs: number[] = json.paramNum[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._paramNum.setKeyAndValueList(ks, vs);
			}
			else if (json.paramNum.getKeys && json.paramNum.getValues) {	//结构体
				const ks2 = json.paramNum.getKeys();
				const vs2 = json.paramNum.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._paramNum.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		if (json.paramStr) {
			const ks: number[] = json.paramStr[0];
			const vs: string[] = json.paramStr[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._paramStr.setKeyAndValueList(ks, vs);
			}
			else if (json.paramStr.getKeys && json.paramStr.getValues) {	//结构体
				const ks2 = json.paramStr.getKeys();
				const vs2 = json.paramStr.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._paramStr.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint8(this._channel);
		byte.writeUint8(this._senderMain);
		byte.writeUint8(this._senderSub);
		byte.writeLongNumber(this._sendTime);
		//数值参
		{
			const ks = this._paramNum.getKeys();
			const vs = this._paramNum.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint8(ks[i]);
				byte.writeLongNumber(vs[i]);
			}
		}
		//字符参
		{
			const ks = this._paramStr.getKeys();
			const vs = this._paramStr.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint8(ks[i]);
				byte.writeString(vs[i]);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._channel = byte.readUint8();
		this._senderMain = byte.readUint8();
		this._senderSub = byte.readUint8();
		this._sendTime = byte.readLongNumber();
		//数值参
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint8();
				const v = byte.readLongNumber();
				this._paramNum.put(k, v);
			}
		}
		//字符参
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint8();
				const v = byte.readString();
				this._paramStr.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): ChatMessage {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ChatMessage.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ChatMessage.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//频道
			if (idx === E_ChatMessage.CHANNEL) {
				const oldv = this._channel;
				this._channel = us[i + 1];
				IAsync.dispatch(eventID, idx, this._channel, oldv);
				i += 2;
				continue;
			}
			//发送者类型
			if (idx === E_ChatMessage.SENDER_MAIN) {
				const oldv = this._senderMain;
				this._senderMain = us[i + 1];
				IAsync.dispatch(eventID, idx, this._senderMain, oldv);
				i += 2;
				continue;
			}
			//发送者类型2(预留)
			if (idx === E_ChatMessage.SENDER_SUB) {
				const oldv = this._senderSub;
				this._senderSub = us[i + 1];
				IAsync.dispatch(eventID, idx, this._senderSub, oldv);
				i += 2;
				continue;
			}
			//发送时间
			if (idx === E_ChatMessage.SEND_TIME) {
				const oldv = this._sendTime;
				this._sendTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._sendTime, oldv);
				i += 2;
				continue;
			}

			//数值参
			if (idx === E_ChatMessage.PARAM_NUM) {
				const k: number = us[i + 1];
				const newv :number = us[i + 2];
				const oldv = this.putParamNum(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}

			//字符参
			if (idx === E_ChatMessage.PARAM_STR) {
				const k: number = us[i + 1];
				const newv :string = us[i + 2];
				const oldv = this.putParamStr(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in ChatMessage with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ChatMessage): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._channel !== other._channel) {
			updates.push(E_ChatMessage.CHANNEL, this._channel);
		}
		if (this._senderMain !== other._senderMain) {
			updates.push(E_ChatMessage.SENDER_MAIN, this._senderMain);
		}
		if (this._senderSub !== other._senderSub) {
			updates.push(E_ChatMessage.SENDER_SUB, this._senderSub);
		}
		if (this._sendTime !== other._sendTime) {
			updates.push(E_ChatMessage.SEND_TIME, this._sendTime);
		}

		//数值参
		{
			const idx = E_ChatMessage.PARAM_NUM;
			const ks1 = this._paramNum.getKeys();
			const ks2 = other._paramNum.getKeys();
			const vs1 = this._paramNum.getValues();
			const vs2 = other._paramNum.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getParamNum(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getParamNum(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//字符参
		{
			const idx = E_ChatMessage.PARAM_STR;
			const ks1 = this._paramStr.getKeys();
			const ks2 = other._paramStr.getKeys();
			const vs1 = this._paramStr.getValues();
			const vs2 = other._paramStr.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getParamStr(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getParamStr(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ChatMessage.TOTAL_EVENT_ID, this.getV(0));
	}

}
